package pck_tramitedocu.pck_src.pck_dao;

import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.mail.MailAuthenticationException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import pck_tramitedocu.pck_src.pck_pojos.Cls_Email;
import pck_tramitedocu.pck_src.pck_pojos.TramiteDocuException;
import pck_tramitedocu.pck_src.pck_utiles.cls_utilitarios;

public class Cls_MailDaoImpl implements Itf_MailDao {

    private JavaMailSenderImpl mailSender;
    private SimpleMailMessage templateMessage;

    public void setMailSender(JavaMailSenderImpl mailSender) {
        this.mailSender = mailSender;
    }

    public void setTemplateMessage(SimpleMailMessage templateMessage) {
        this.templateMessage = templateMessage;
    }

    public String sendMensaje(Cls_Email email) throws TramiteDocuException {
        if (email.getEmail().isEmpty()) {
            return "";
        }
        MimeMessage message = this.mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom("controlservicee@gmail.com", email.getRemitente());
            helper.setTo(cls_utilitarios.getArrayStringFromList(email.getEmail()));
            helper.setSubject(email.getMensateSubject());
            helper.setText(email.getMensajeText(), true);
            this.mailSender.send(message);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Cls_MailDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
            throw new TramiteDocuException(ex.getClass().getSimpleName());
        } catch (MessagingException ex) {
            Logger.getLogger(Cls_MailDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
            throw new TramiteDocuException(ex.getClass().getSimpleName());
        } catch (MailAuthenticationException ex) {
            Logger.getLogger(Cls_MailDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
            throw new TramiteDocuException(ex.getClass().getSimpleName());
        } catch (Exception ex) {
            Logger.getLogger(Cls_MailDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
            throw new TramiteDocuException(ex.getClass().getSimpleName());
        }
        return "ok";
    }
}